﻿using EntityFramework.Data.Core;
using Framework.IOC;
using IRepositories.Core;
using Repositories.Test.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
namespace Repositories.Test.Service
{
    public class UserService : ServiceBase, IUserService
    {
        IEFRepository<User> userRepository;
        IEFRepository<Log> logRepository;
        IEFRepository<Department> deptRepository;
        IUnitOfWork db;
        public UserService(IUnitOfWork db, IEFRepository<User> _userRepository, IEFRepository<Log> _logRepository)
        {
            this.userRepository = _userRepository;
            this.logRepository = _logRepository;
            this.userRepository.SetDbContext(db);
            this.logRepository.SetDbContext(db);
            this.db = db;

        }

        public UserService()
        {
            userRepository = ServiceLocator.Instance.GetService<IEFRepository<User>>();
            deptRepository = ServiceLocator.Instance.GetService<IEFRepository<Department>>();
            logRepository = ServiceLocator.Instance.GetService<IEFRepository<Log>>();
            db = ServiceLocator.Instance.GetService<IUnitOfWork>();
            this.userRepository.SetDbContext(db);
            this.logRepository.SetDbContext(db);
            this.deptRepository.SetDbContext(db);




        }
        public void Add(User user)
        {
            TransactionScopeNoMsdtc.UsingTransactionNoMsdtc(db, () =>
            {
                userRepository.GetModel().Include(p => p.Department);
                userRepository.Insert(user);
                //logRepository.Insert(new Log() { LogConent = user.Department.DeptName });
                //logRepository.BulkInsert(new Log[] { new Log() { LogConent = user.Department.DeptName } });
                userRepository.Update(p => p.UserId == 1, u => new User { UserName = "1021", Age = 85 });
                //throw new Exception("主动异常");
                
            });
            
        }
        public void Update(User user)
        {

            userRepository.Update(p => p.UserId == user.ID, u => new User { UserName = user.UserName, Age = user.Age });
        }

        public void GetList()
        {
            //var id = new EFRepository<Department>(new TestEFDbContext()).GetModel().FirstOrDefault().ID;
            //var model= userRepository.GetModel(p => p.Department.DeptId == id);
            var list = userRepository.GetModel().Join(logRepository.GetModel(), u => u.Department.DeptName, l => l.LogConent, (u, l) => u).ToList();
            int i = 0;
        }
    }
}
